package itsm.isperp.workflow.cmd;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.module.service.bpm.BpmActionHistoryService;

import java.util.List;

import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;

public class JumpCmd implements Command<Object> {
	private String activityId;
	private String procInstId;
	private String jumpOrigin;
	private String actionUserId;
	private String jumpName;

	public JumpCmd(String procInstId, String activityId, String actionUserId,
			String jumpOrigin) {
		this.activityId = activityId;
		this.procInstId = procInstId;
		this.jumpOrigin = jumpOrigin;
		this.actionUserId = actionUserId;
	}

	public JumpCmd(String procInstId, String activityId, String actionUserId,
			String jumpName, String jumpOrigin) {
		this.activityId = activityId;
		this.procInstId = procInstId;
		this.jumpName = jumpName;
		this.jumpOrigin = jumpOrigin;
		this.actionUserId = actionUserId;
	}

	public Object execute(CommandContext commandContext) {

		BpmActionHistoryService bpmActionHistoryService = ContextHolder
				.getSpringBean("bpmActionHistoryService");

		ExecutionEntity executionEntity = commandContext
				.getExecutionEntityManager().findExecutionById(procInstId);
		// IdentityLinkEntityManager idm = commandContext
		// .getIdentityLinkEntityManager();
		// idm.deleteIdentityLinksByProcInstance(executionId);
		for (TaskEntity taskEntity : commandContext.getTaskEntityManager()
				.findTasksByExecutionId(procInstId)) {
			commandContext.getTaskEntityManager().deleteTask(taskEntity,
					jumpOrigin, false);

			// idm.deleteIdentityLinksByTaskId(taskEntity.getId());

			bpmActionHistoryService.save(procInstId,
					executionEntity.getBusinessKey(), taskEntity.getId(),
					activityId,
					(jumpName != null ? jumpName : taskEntity.getName()),
					actionUserId, jumpOrigin);

		}
		List<ExecutionEntity> childen = commandContext
				.getExecutionEntityManager()
				.findChildExecutionsByProcessInstanceId(procInstId);

		if (childen != null) {
			for (ExecutionEntity ee : childen) {
				for (TaskEntity taskEntity : commandContext
						.getTaskEntityManager().findTasksByExecutionId(
								ee.getId())) {
					commandContext.getTaskEntityManager().deleteTask(
							taskEntity, jumpOrigin, false);

				}
			}
		}

		ProcessDefinitionImpl processDefinition = executionEntity
				.getProcessDefinition();
		ActivityImpl activity = processDefinition.findActivity(activityId);

		executionEntity.executeActivity(activity);

		return null;
	}
}
